import axios from 'axios'
import { UNIFIED_LOGIN_CONFIG } from '@/config'
import { useUserStore } from '@/stores/user'

// 创建axios实例
const request = axios.create({
  baseURL: UNIFIED_LOGIN_CONFIG.apiBaseUrl,
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    
    // 如果有token，自动添加到请求头
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    
    console.log('[Request]', config.method.toUpperCase(), config.url)
    return config
  },
  error => {
    console.error('[Request Error]', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    console.log('[Response]', response.config.url, res)
    
    // 如果响应格式包含code字段
    if (res.code !== undefined) {
      if (res.code === 200) {
        return res
      } else {
        console.error('[Response Error]', res.message)
        return Promise.reject(new Error(res.message || '请求失败'))
      }
    }
    
    return res
  },
  error => {
    console.error('[Response Error]', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      // token过期或无效
      if (status === 401) {
        const userStore = useUserStore()
        userStore.clearAuthInfo()
        
        // 跳转到登录
        window.location.href = getLoginUrl()
        
        return Promise.reject(new Error('登录已过期，请重新登录'))
      }
      
      return Promise.reject(new Error(data.message || '请求失败'))
    }
    
    return Promise.reject(error)
  }
)

// 获取登录URL
function getLoginUrl() {
  const callback = encodeURIComponent(window.location.origin + window.location.pathname)
  return `${UNIFIED_LOGIN_CONFIG.loginUrl}?callback=${callback}&app_name=${UNIFIED_LOGIN_CONFIG.appName}&app_id=${UNIFIED_LOGIN_CONFIG.appId}`
}

export default request

